package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.PermissionService;
import cn.wolfcode.service.RoleService;
import cn.wolfcode.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    //@RequirePermission(name="角色列表",expression = "role:list")
    @RequiresPermissions(value = {"role:list","角色列表"}, logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
       PageInfo<Role> pageResult = roleService.query(qo);

        model.addAttribute("pageResult", pageResult);

        return "role/list";
    }

    @RequirePermission(name="角色删除",expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null){
            roleService.delete(id);
        }
        return "redirect:/role/list.do";
    }

    @RequestMapping("/input")
    public String input(Long id,Model model) {
        //查询所有的权限 并共享到页面中
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);


        if (id != null){
            Role role = roleService.selectById(id);
            model.addAttribute("role",role);
        }

        return "role/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids) {

        if (role.getId() != null){
            roleService.update(role,ids);
        }else {
            roleService.save(role,ids);
        }
        return "redirect:/role/list.do";
    }

}
